// pages/base/base.js
const app =getApp()
var bmap = require('../../libs/bmap-wx.js'); 
var wxMarkerData = [];
var util = require('../../utils/util.js');  //引入时间 
Page({
  /**
   * 页面的初始数据
   */
  data: {
        time:'',
        aqi:'',  //小提示
        cityNm:"",  //定位
        realTime :{},  //当时天气
        today:{},//今天
        futureHour:{},  //未来24小时天气，未来逐小时预报
        futureDay:{}, //未来七天的天气
        lifeIndex:{}, //生活指数
        inputContent:'',//输入框内容
        futureHourNum:[],
         weatherIcon:[],  //天气图标

         ct_liattr:'',
         ct_liDese:'',
         uv_liattr:'',
         uv_liDese:'',
         xt_liattr:'',
         xt_liDese:'',
         xc_liattr:'',
         xc_liDese:'',

         
  },
    // PM2.5 AQI对照 wtAqi
    
    //点击查询，查询城市天气
    mysubmit:function(res){
      // console.log(res);
      this.setData({
        cityNm:res.detail.value.icity
      })
      this.getWeatherInfo();     
      //文本框输入内容之后，清空内容
      this.setData({
        inputContent: ''
       })
    },

    onInputFieldChange(event) {
      // 设置全局变量
      this.setData({ inputContent: event.detail.value });
    },

      /**
     * 点击清除按钮，清除内容
     */
    onClearBtnClick() {
      this.setData({
        inputContent: '',
       
      })
    },

    

    //获取天气信息
    getWeatherInfo:function(){
      var self =  this;
      // console.log(self.data.ct_liDese)
      wx.request({     //调用服务端接口
        url: 'https://sapi.k780.com',
        data:{
          cityNm:self.data.cityNm,
          app:"weather.realtime",
          ag:"today,futureDay,lifeIndex,futureHour",
          appkey:"60273",
          sign:"8d88ea96e34e7326b4e549babb9263c2"
        },
        success(res){
          if (res.data.success == '0') {
            self.setData({ 
              cityNm: '??' 
          });
            wx.showModal({
              title: '错误提示',
              content: '很抱歉，没有该城市的天气信息，请输入正确的名称',
              success: function (res) {
                if (res.confirm) {//这里是点击了确定以后
                  console.log('用户点击确定')   
                } else {//这里是点击了取消以后
                  console.log('用户点击取消')
                }   
              }
            })
            return false;
          }
          self.setData({
                        
            realTime:res.data.result.realTime,
            futureHour:res.data.result.futureHour,
            futureDay:res.data.result.futureDay,
            lifeIndex:res.data.result.today.lifeIndex,

            ct_liattr:res.data.result.today.lifeIndex.ct.liAttr,
            ct_liDese:res.data.result.today.lifeIndex.ct.liDese,

            uv_liattr:res.data.result.today.lifeIndex.uv.liAttr,
            uv_liDese:res.data.result.today.lifeIndex.uv.liDese,

            xc_liattr:res.data.result.today.lifeIndex.xc.liAttr,
            xc_liDese:res.data.result.today.lifeIndex.xc.liDese,

            xt_liattr:res.data.result.today.lifeIndex.xt.liAttr,
            xt_liDese:res.data.result.today.lifeIndex.xt.liDese,
          })

          let futureHour = res.data.result.futureHour
          for(var i=0;i<futureHour.length;i++){
          var now = self.data.futureHour;
           const arr = []
           for (var i = 0; i < now.length; ++i) {
            arr.push(self.formatTime((now[i].dateYmdh)))
          }
          self.setData({
            futureHourNum:arr
          })

           //PM2.5 AQI对照 wtAqi 添加小提示
           let  wtAqi =res.data.result.realTime.wtAqi

           if(wtAqi >0 && wtAqi <=50){
             self.setData({
               aqi:"指标为优，参加户外活动呼吸清新空气"
             })

           }
           else if (wtAqi >51 && wtAqi <=100) {
           self.setData({
             aqi:"指标为良，可以正常进行室外活动"
           })
           
           }
           else if (wtAqi >101 && wtAqi <=150){
             self.setData({
               aqi:"轻度污染，敏感人群减少体力消耗大的户外活动"
             })
           }
           else if (wtAqi >151 && wtAqi <=200) {
           self.setData({
             aqi:"中度污染，对敏感人群影响较大"
           })
         }
           
         else if (wtAqi >201 && wtAqi <=250) {
           self.setData({
             aqi:"重度污染，所有人应适当减少室外活动"
           })
         }
            else if (wtAqi >300) {
           self.setData({
             aqi:"严重污染,尽量不要留在室外"
           })
        }
      }
          wx.showToast({
            title: '获取天气成功',
            icon: 'success',
            duration: 2000//持续的时间
          })         
        },
      })
    },
    formatTime : function(now) {
      var time = new Date(now);
      var hour=time.getHours();     //返回日期中的小时数（0到23）
      var minute=time.getMinutes(); //返回日期中的分钟数（0到59）

      var h = hour<10?'0'+hour:hour
      var m = minute<10?'0'+minute:minute
      return h+":"+m;
  },
   
   //获取天气图标
   getIconInfo:function(){
     let that = this 
    wx.request({     //调用服务端接口
      url: 'https://sapi.k780.com',
      data:{
        app:"weather.wtype",
        appkey:"60273",
        sign:"8d88ea96e34e7326b4e549babb9263c2"
      },
      success(res){
      // console.log(res);
      let icon = res.data.result
      // console.log(icon)
   },
  })
},

  onLoad: function (options) {
// 调用函数时，传入new Date()参数，返回值是日期和时间
    var time = util.formatTime(new Date());
// 再通过setData更改Page()里面的data，动态更新页面的数据
    this.setData({
     time: time,
    });
    var that = this; 
    // 新建百度地图对象 
    var BMap = new bmap.BMapWX({ 
        ak: 'ZUEhONOGcvAEPaq91hc7ayOVGyq9cUjV' 
    }); 
    var fail = function(data) {    
        // wx.showModal({
        //   title: '错误提示',
        //   content: '很抱歉，您未打开或授权定位服务，请打开或授权后重新载入小程序！',
        //   success: function (res) {
        //     if (res.confirm) {//这里是点击了确定以后
        //       console.log('用户点击确定')   
        //     } else {//这里是点击了取消以后
        //       console.log('用户点击取消')
        //     }   
        //   }
        // })
        wx.getLocation({
          success: res => {
            console.log(res);
          },
          fail: e => {
            console.log(e);
            // 判断用户是否拒绝了授权
            wx.getSetting({
              success: res => {
                if (typeof(res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
                  // 用户拒绝了授权
                  wx.showModal({
                    title: '错误提示',
                    content: '很抱歉，您未打开或授权定位服务，请打开或授权后重新载入小程序！',
                    success: res => {
                      if (res.confirm) {
                        // 跳转设置页面
                        wx.openSetting({
                          success: res => {
                            if (res.authSetting['scope.userLocation']) {
                              // 授权成功，重新定位
                              wx.getLocation({
                                success: res => {}
                              });
                            } else {
                              // 没有允许定位权限
                              wx.showToast({
                                title: '很抱歉，您未打开或授权定位服务，请打开或授权后重新载入小程序！',
                                icon: 'none'
                              });
                            }
                          }
                        });
                      }
                    }
                  });
                  that.setData({
                    cityNm : '北京',
                });
                  that.getWeatherInfo1();
                  that.getIconInfo();
                }
              }
            });
        }});

    }; 
    var success = function(data) { 
        wxMarkerData = data.wxMarkerData;
        that.setData({
          cityNm : data.originalData.result.addressComponent.city.substring(0, 2),
      });
        that.getWeatherInfo();
        that.getIconInfo();

    } 
    // 发起regeocoding检索请求 
    BMap.regeocoding({ 
        fail: fail, 
        success: success, 
        iconPath: '../../img/marker_red.png', 
        iconTapPath: '../../img/marker_red.png' 
    }); 

    wx.onNetworkStatusChange(
      function(res) {
        console.log(res)
        if(res.isConnected == false){
          wx.showModal({
            title: '错误提示',
            content: '很抱歉，您未打开网络，请打开网络后重新载入小程序！',
            success: function (res) {
              if (res.confirm) {//这里是点击了确定以后
                console.log('用户点击确定')   
              } else {//这里是点击了取消以后
                console.log('用户点击取消')
              }   
            }
          })
        }
    }
    )

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    Page({
      onShareAppMessage() {
        const promise = new Promise(resolve => {
          setTimeout(() => {
            resolve({
              title: '玖玖天气'
            })
          }, 2000)
        })
        return {
          title: '玖玖天气',
          path: '/pages/base/base',
          promise 
        }
      }
    })
  },
  	//用户点击右上角分享朋友圈
	onShareTimeline: function () {
		return {
        title: '玖玖天气',
        path: '/pages/base/base',
	      query: {
	        key: value
	      },
	    }
	},
  //下拉刷新
  
  onPullDownRefresh:function()
  {
    let that = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    //模拟加载
    setTimeout(function()
    {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 2000//持续的时间
      })
    },1000);

      // // 显示顶部刷新图标
      // wx.showNavigationBarLoading();
      // //关闭当前非tabbar页面，跳转到应用内的某个页面
      // //如果不行使用wx.reLaunch，关闭所有页面，打开到应用内的某个页面
      // wx.redirectTo({
      // //加载页面地址
      //   url: '/pages/base/base',
      //   success:function(res){
      //     // 隐藏导航栏加载框
      //     wx.hideNavigationBarLoading();
      //     // 停止下拉动作
      //     wx.stopPullDownRefresh();
      //   }
      // })
    

//  下拉刷新时  显示实时时间
 setTimeout(function()
 {
     // 调用函数时，传入new Date()参数，返回值是日期和时间
     var time = util.formatTime(new Date());
     // 再通过setData更改Page()里面的data，动态更新页面的数据
      that.setData({
        time: time,
       });
},1000);
  },
      //获取默认天气信息
      getWeatherInfo1:function(){
        var self =  this;
        // console.log(self.data.ct_liDese)
        wx.request({     //调用服务端接口
          url: 'https://sapi.k780.com',
          data:{
            cityNm:self.data.cityNm,
            app:"weather.realtime",
            ag:"today,futureDay,lifeIndex,futureHour",
            appkey:"60273",
            sign:"8d88ea96e34e7326b4e549babb9263c2"
          },
          success(res){
            self.setData({
                          
              realTime:res.data.result.realTime,
              futureHour:res.data.result.futureHour,
              futureDay:res.data.result.futureDay,
              lifeIndex:res.data.result.today.lifeIndex,
  
              ct_liattr:res.data.result.today.lifeIndex.ct.liAttr,
              ct_liDese:res.data.result.today.lifeIndex.ct.liDese,
  
              uv_liattr:res.data.result.today.lifeIndex.uv.liAttr,
              uv_liDese:res.data.result.today.lifeIndex.uv.liDese,
  
              xc_liattr:res.data.result.today.lifeIndex.xc.liAttr,
              xc_liDese:res.data.result.today.lifeIndex.xc.liDese,
  
              xt_liattr:res.data.result.today.lifeIndex.xt.liAttr,
              xt_liDese:res.data.result.today.lifeIndex.xt.liDese,
            })
  
            let futureHour = res.data.result.futureHour
            for(var i=0;i<futureHour.length;i++){
            var now = self.data.futureHour;
             const arr = []
             for (var i = 0; i < now.length; ++i) {
              arr.push(self.formatTime((now[i].dateYmdh)))
            }
            self.setData({
              futureHourNum:arr
            })
  
             //PM2.5 AQI对照 wtAqi 添加小提示
             let  wtAqi =res.data.result.realTime.wtAqi
             if(wtAqi >0 && wtAqi <=50){
               self.setData({
                 aqi:"指标为优，参加户外活动呼吸清新空气"
               })
               
             }
             else if (wtAqi >51 && wtAqi <=100) {
             self.setData({
               aqi:"指标为良，可以正常进行室外活动"
             })
   
             }
             else if (wtAqi >101 && wtAqi <=150){
               self.setData({
                 aqi:"轻度污染，敏感人群减少体力消耗大的户外活动"
               })
             }
             else if (wtAqi >151 && wtAqi <=200) {
             self.setData({
               aqi:"中度污染，对敏感人群影响较大"
             })
           }
             
           else if (wtAqi >201 && wtAqi <=250) {
             self.setData({
               aqi:"重度污染，所有人应适当减少室外活动"
             })
           }
              else if (wtAqi >300) {
             self.setData({
               aqi:"严重污染,尽量不要留在室外"
             })
          }
        }
            
          },
        })
      },

})